<?php

namespace StudyBuddy\Modules\Blogger;

/**
 * Class for posting Questions ans Answers
 * to Blogger via API
 *
 */
class PostBlogger extends \StudyBuddy\Observer {

    /**
     * blogger API Config array
     * a BLOGGER section from !config.ini
     *
     * @var array
     */
    protected $aConfig;

    public function main() {

        $a = $this->oRegistry->Request->getArray();
        if (empty($a['blogger'])) {
            d('blogger checkbox not checked');
            /**
             * Set the preference in Viewer object
             * for that "Post to blogger" checkbox to be not checked
             * This is just in case it was checked before
             */
            $this->oRegistry->Viewer['b_bg'] = false;

            return;
        }

        /**
         * First if this site does not have support for blogger API
         * OR if User does not have blogger credentials then
         * there is nothing to do here
         * This is unlikely because user without blogger credentials
         * will not get to see the checkbox to post to blogger
         * but still it's better to check just to be sure
         */
        if (!extension_loaded('curl')) {
            d('curl extension not present, exiting');

            return;
        }

        try {

            $this->aConfig = $this->oRegistry->Ini->getSection('BLOGGER');

            if (empty($this->aConfig)
                    || empty($this->aConfig['OAUTH_KEY'])
                    || empty($this->aConfig['OAUTH_SECRET'])) {
                d('blogger API not enabled on this site');

                return;
                ;
            }
        } catch (\StudyBuddy\IniException $e) {
            d('Ini Exception: ' . $e->getMessage());

            return;
        }

        if (null === $this->oRegistry->Viewer->getBloggerToken()) {
            d('User does not have Blogger token');
            return;
        }

        /**
         * Now we know that user checked that checkbox
         * to post content to blogger
         * and we now going to save this preference
         * in User object
         *
         */
        $this->oRegistry->Viewer['b_bg'] = true;
        d('cp $this->eventName: ' . $this->eventName);
        switch ($this->eventName) {
            case 'onNewQuestion':
            case 'onNewAnswer':
                d('cp');
                $this->post();
                break;
        }
    }

    /**
     * Post to blogger blog
     *
     */
    protected function post() {
        d('cp');
        try {
            d('cp');
            $oBlogger = new ApiClient($this->oRegistry);
            d('cp');
            $User = $this->oRegistry->Viewer;
            d('cp');
            if (false === $oBlogger->setUser($User)) {
                d('User does not have Blogger Oauth credentials');

                return;
            }
            d('cp');
            $reward = \StudyBuddy\Points::SHARED_CONTENT;
            $oResource = $this->obj;
            d('cp');
            $oAdapter = new BloggerPostAdapter($this->oRegistry);
            d('cp');
        } catch (\Exception $e) {
            d('Unable to post to blogger because of this exception: ' . $e->getMessage() . ' in file: ' . $e->getFile() . ' on line: ' . $e->getLine());
            return;
        }
        d('cp');
        $func = function() use ($oBlogger, $oAdapter, $oResource, $User, $reward) {

                    $result = null;

                    try {
                        $result = $oBlogger->add($oAdapter->makeEntry($oResource));
                    } catch (\Exception $e) {

                        return;
                    }

                    if (!empty($result) && is_numeric($result)) {

                        $User->setReputation($reward);

                        /**
                         * Also save blogger post id to QUESTIONS or ANSWERS
                         * collection.
                         * This way later on (maybe way later...)
                         * We can add a function so that if user edits
                         * Post on the site we can also edit it
                         * on blogger via API
                         * Can also delete from blogger if Resource
                         * id deleted
                         *
                         */
                        $oResource['blogger_id'] = $result;
                        $oResource->save();
                    }
                };
        //$func();
        \StudyBuddy\runLater($func);
    }

}
